<?php

// 公共助手函数

use Symfony\Component\VarExporter\VarExporter;
use think\exception\HttpResponseException;
use think\Response;
use think\Db;

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @param int    $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $linedata = array_intersect_key($result[$n], $curr);
                    $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed   $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
        $replaced = [];
        $count = 0;

        //判断是否是对象
        if (is_resource($data) || is_object($data)) {
            return var_export($data, $return);
        }

        //判断是否有特殊的键名
        $specialKey = false;
        array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
            if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
                $specialKey = true;
            }
        });
        if ($specialKey) {
            return var_export($data, $return);
        }
        array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
            if (is_object($value) || is_resource($value)) {
                $replaced[$count] = var_export($value, true);
                $value = "##<{$count}>##";
            } else {
                if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
                    $index = array_search($value, $replaced);
                    if ($index === false) {
                        $replaced[$count] = var_export($value, true);
                        $value = "##<{$count}>##";
                    } else {
                        $value = "##<{$index}>##";
                    }
                }
            }
            $count++;
        });

        $dump = var_export($data, true);

        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
        $dump = preg_replace('#\)$#', "]", $dump); //End

        if ($replaced) {
            $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
                return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
            }, $dump);
        }

        if ($return === true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                $response = Response::create('跨域检测无效', 'html', 403);
                throw new HttpResponseException($response);
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                $response = Response::create('', 'html');
                throw new HttpResponseException($response);
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            $response = Response::create('请求无权访问', 'html', 403);
            throw new HttpResponseException($response);
        }
    }
}

if (!function_exists('build_suffix_image')) {
    /**
     * 生成文件后缀图片
     * @param string $suffix 后缀
     * @param null   $background
     * @return string
     */
    function build_suffix_image($suffix, $background = null)
    {
        $suffix = mb_substr(strtoupper($suffix), 0, 4);
        $total = unpack('L', hash('adler32', $suffix, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $background = $background ? $background : "rgb({$r},{$g},{$b})";

        $icon = <<<EOT
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
        </svg>
EOT;
        return $icon;
    }
}


/**
 * CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug 调试开启 默认false
 * @return mixed
 */
function http_request($url, $method = "GET", $postfields = null, $headers = array(), $returnArr = true, $debug = false)
{
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 10); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestInfo = curl_getinfo($ci);
    $httpCode = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestInfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    //return array($httpCode, $response,$requestInfo);
    if ($httpCode == 200) {
        return $returnArr ? json_decode($response, true) : $response;
    }
    return false;

}

/**
 * 计算地球两点之间的距离
 * @param $lat1
 * @param $lon1
 * @param $lat2
 * @param $lon2
 * @param float $radius 星球半径 M
 * @return float
 */
function distance($lat1, $lon1, $lat2, $lon2, $radius = 6378137)
{
    $rad = floatval(M_PI / 180.0);

    $lat1 = floatval($lat1) * $rad;
    $lon1 = floatval($lon1) * $rad;
    $lat2 = floatval($lat2) * $rad;
    $lon2 = floatval($lon2) * $rad;

    $theta = $lon2 - $lon1;

    $dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta));

    if ($dist < 0) {
        $dist += M_PI;
    }
    return $dist = $dist * $radius;
}

/**
 * 往图片上写字
 * @param $image   图片资源
 * @param float $size 字体大小
 * @param float $angle 角度
 * @param int $x x轴,大概是字的左下角
 * @param int $y y轴
 * @param array $color 颜色[0,0,0]
 * @param null $fontFile 字体
 * @param string $text 文字
 * @param int $width 每行占的宽度
 * @param int $lineNum 行数
 * @param int $lineHeight 行高
 * @return mixed    操作后的图片资源
 */
function writeText2Image($image, float $size = 33.25, float $angle = 0, int $x = 0, int $y = 0, array $color = [220, 20, 60], $fontFile = null, string $text = '', $width = 670, $lineNum = 1, $lineHeight = 50)
{
    $fontFile = $fontFile ?? './shareimg/font/msyh.ttf';
    $text = mb_convert_encoding($text, "UTF-8");
    $text = to_entities($text);
    $r = [];
    for ($i = 0; $i < iconv_strlen($text); $i++) {
        if (count($r) < $lineNum) {
            $t = imagettfbbox($size, 0, $fontFile, iconv_substr($text, 0, $i));
            if ($t[2] - $t[0] > (count($r) == 1 ? ($width / 4 * 3) : $width)) {
                $tempLength = $i - 1;
                $r[] = iconv_substr($text, 0, $tempLength) . (count($r) == 1 ? '...' : '');
                $text = iconv_substr($text, $tempLength);
                $i = -1;
            }
        }
    }
    if ($text) $r[] = $text;
    //循环写字
    for ($i = 0; $i < count($r); $i++) {
        if ($i < $lineNum) {
            imageTtfText($image, $size, $angle, $x, $y + $i * $lineHeight, imagecolorallocate($image, $color[0], $color[1], $color[2]), $fontFile, $r[$i]);
            //重复写文字，仿佛实现了字体增粗的效果
//            imageTtfText($image, $size, $angle, $x, $y + $i * $lineHeight+1, imagecolorallocate($image, $color[0], $color[1], $color[2]), $fontFile, $r[$i]);
        }
    }
    return $image;
}


function to_entities($string)
{
    $len = strlen($string);
    $buf = "";
    for($i = 0; $i < $len; $i++){
        if (ord($string[$i]) <= 127){
            $buf .= $string[$i];
        } else if (ord ($string[$i]) <192){
            //unexpected 2nd, 3rd or 4th byte
            $buf .= "&#xfffd";
        } else if (ord ($string[$i]) <224){
            //first byte of 2-byte seq
            $buf .= sprintf("&#%d;",
                ((ord($string[$i + 0]) & 31) << 6) +
                (ord($string[$i + 1]) & 63)
            );
            $i += 1;
        } else if (ord ($string[$i]) <240){
            //first byte of 3-byte seq
            $buf .= sprintf("&#%d;",
                ((ord($string[$i + 0]) & 15) << 12) +
                ((ord($string[$i + 1]) & 63) << 6) +
                (ord($string[$i + 2]) & 63)
            );
            $i += 2;
        } else {
            //first byte of 4-byte seq
            $buf .= sprintf("&#%d;",
                ((ord($string[$i + 0]) & 7) << 18) +
                ((ord($string[$i + 1]) & 63) << 12) +
                ((ord($string[$i + 2]) & 63) << 6) +
                (ord($string[$i + 3]) & 63)
            );
            $i += 3;
        }
    }
    return $buf;
}

/**
 * 根据图片后缀不同，使用不同的函数创建
 * @param $path
 * @return resource
 */
function getImageCreate($path)
{
    $ext = getImageExt($path);
    $srcImg = '';
    switch ($ext) {
        case 'jpg':
            $srcImg = imagecreatefromjpeg($path);
            break;
        case 'jpeg':
            $srcImg = imagecreatefromjpeg($path);
            break;
        case 'png':
            $srcImg = imagecreatefrompng($path);
            break;
    }
    return $srcImg;
}

/**
 * 判断图片后缀
 * @param $path
 */
function getImageExt($path)
{
    $imageSize = getimagesize($path);
    $imageMime = $imageSize['mime'];
    $extInfo = explode('/', $imageMime);
    return $extInfo[1];
}


/**
 * 获得OSS图片路径前缀
 * @return string
 */
function getOssPath()
{
    return 'https://oss.chbcplus.com';
}

/**
 * 格式化数字
 * @param float $number
 * @param int $decimals
 * @return string
 */
function numberFormat($number = 0.00, $decimals = 2)
{
    return number_format($number, $decimals, '.', '');
}

/**
 * 获取指定长度的随机字符串，英文和数字
 * @param int $length 长度
 * @param boolean $isNum 是否是纯数字
 * @return string
 */
function getRandStr($length = 6, $isNum = true)
{
    //字符组合
//    $str = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ0123456789';
//    $str = '1234567890';
    $str = $isNum ? '1234567890' : 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ0123456789';
    $len = strlen($str) - 1;
    $randStr = '';
    for ($i = 0; $i < $length; $i++) {
        $num = mt_rand(0, $len);
        $randStr .= $str[$num];
    }
    return $randStr;
}

/**
 * 判定当前是否是https
 * @return bool
 */
function is_https()
{
    if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
        return true;
    } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return true;
    }
    return false;
}

/**
 * 删除服务器的某张图片
 * @param string $imagePath
 * @return bool
 */
function delete_image(string $imagePath = '')
{
    $imagePath = trim($imagePath);
    if ($imagePath == '') return false;
    if (stripos($imagePath, '.') !== 0) {
        if (stripos($imagePath, '/') !== 0) {
            $imagePath = './' . $imagePath;
        } else {
            $imagePath = '.' . $imagePath;
        }
    }
    try {
        return unlink($imagePath);
    } catch (\think\Exception $exception) {
        //删除失败了
    }
    return false;
}


/**
 * 生成数据库不存在的用户名
 * @return string
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getUniqueUsername()
{
    $username = getRandStr(10, false);
    $user = (new \app\common\model\User())->where(['username' => $username])->find();
    if ($user) {
        return getUniqueUsername();
    }
    return $username;
}

function getWebappHtml($ysid, $appid, $path, $html, $style, $extend = [])
{
    if (isset($extend['wm_shop_id']) && $extend['wm_shop_id'] != '') $path = $path . $extend['wm_shop_id'];

    $html = '<wx-open-launch-weapp id="launch-btn" username="'
        . $ysid
        . '" path="'
        . $path
        . '" @launch="handleLaunchFn" @error="handleErrorFn"><template><style>'
        . $style
        . '</style>'
        . $html
        . '</template></wx-open-launch-weapp>';
    return $html;
}

/**
 * 临时输出文件使用
 * @param null $data
 * @param string $pre
 * @param null $fileName
 */
function p($data = null, $pre = '', $fileName = null)
{
    try {
        $path = ROOT_PATH . 'syp_log/trnall_dev/';
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }
        $fileName = $fileName ?? date("Ymd") . '.txt';
        $text = "\r\n" . date("H:i:s") . "【" . $pre . "】" . "\r\n" . json_encode($data) . "\r\n";
        file_put_contents($path . $fileName, $text, 8);
    } catch (\think\Exception $exception) {
//        echo $exception->getMessage();
    }
}


function validatePhoneNumber($phoneNumber) {
    // 移除手机号中的空格和短横线
    $phoneNumber = str_replace([' ', '-'], '', $phoneNumber);

    // 检查手机号长度
    if (strlen($phoneNumber) != 11) {
        return false;
    }

    // 检查手机号是否只包含数字
    if (!ctype_digit($phoneNumber)) {
        return false;
    }

    // 检查手机号是否以 1 开头
    if (substr($phoneNumber, 0, 1) != '1') {
        return false;
    }

    // 验证通过
    return true;
}

// 对时效性要求高的场景使用
function order_count($user_id)
{
    $db2 = Db::connect(config('database.db2'));
    $num = (int)Db::name('play_order')->where(['user_id'=>$user_id,'order_status'=>['in',[3,-6,-7,-8,-9,-4]]])->count();
    $num2 = (int)Db::name('mtofficial_order')->where(['user_id'=>$user_id,'order_status'=>3])->count();
    return intval($num+$num2);
}

// 对时效性要求不高的场景使用
function order_count_read($user_id)
{
    $db2 = Db::connect(config('database.db2'));
    $num = (int)$db2->name('play_order')->where(['user_id'=>$user_id,'order_status'=>['in',[3,-6,-7,-8,-9,-4]]])->count();
    $num2 = (int)$db2->name('mtofficial_order')->where(['user_id'=>$user_id,'order_status'=>3])->count();
    return intval($num+$num2);
}

// 是否需要商家复审
// userorder:用户下单数，back_money：返利金额,is_pay：是否是前台发布,is_limited:受限用户（全部复审）,is_sjzp:是否是自配送店铺，ljps：是否是立即配送,cps_id:是否是cps订单
// false 不需要复审 true需要
function is_fushen($is_sjzp,$userorder,$back_money,$is_pay,$is_limited=0,$ljps=1,$create_dt='',$play_label=0,$cps_id=0,$shop_type=1)
{
    if ($is_pay==1) {
        return false;
    }
    if ($is_limited) {
        return "账户近期有“违规行为”订单需商家复审，完成6笔订单，且无异常恢复正常使用~";
    }
    // 如果不是新用户专享，如果抢单时间到提交凭证时间不超过25分需要商家复审
    // if ($create_dt && time()-strtotime($create_dt)<1500 && $play_label!=2) {
    //     return true;
    // }
    // 第一单大于19进入复审
    if ($userorder==0 && $back_money>=19) {
        return "该笔订单为“大额返利”需商家复审!大约需3个工作日左右，如超出时间请联系吃喝不愁客服。";
    }
    // if ($shop_type==2) return false;
    // 如果是自配送店铺，且不是立即配送
    if ($is_sjzp && !$ljps) {
        if (($userorder>100 && $back_money>=60) || ($userorder>30 && $userorder<=100 && $back_money>=40) || ($userorder>6 && $userorder<=30 && $back_money>=30) || $userorder<=6) {
            return "该店铺为“商家自配送”店铺，订单需商家复审，如有疑问请联系吃喝不愁客服。";
        }
    } else {
        if ($cps_id) {
            if (($userorder>100 && $back_money>=60) || ($userorder>30 && $userorder<=100 && $back_money>=40) || ($userorder<=30 && $back_money>=35)) {
                return "该笔订单为“大额返利”需商家复审!大约需3个工作日左右，如超出时间请联系吃喝不愁客服。";
            }
        } else {
            if (($userorder>100 && $back_money>=60) || ($userorder>30 && $userorder<=100 && $back_money>=40) || ($userorder<=30 && $back_money>=30)) {
                return "该笔订单为“大额返利”需商家复审!大约需3个工作日左右，如超出时间请联系吃喝不愁客服。";
            }
        }
    }
    return false;
}


function match_dot($content)
{
    preg_match_all('/[\p{Han}A-Za-z][.][\p{Han}A-Za-z]/u', $content, $matches);
    if (isset($matches[0]) && count($matches[0])) {
        foreach ($matches[0] as $m) {
            $m2 = str_replace('.', '', $m);
            $content =  str_replace($m, $m2, $content);
        }
    }
    return $content;
}

/**
 * [max_return description]
 * @param  [type] $maxCommission [description]
 * @param  [type] $ratio         [description]
 * @return [type] $type          1-美团2-饿了么3-云瞻美团活动
 */
function max_return($maxCommission,$ratio,$type=1)
{
    if ($type==1) {
        if ($ratio<5500) {
            return round($maxCommission*0.93,2);
        } else {
            return round($maxCommission*0.83,2);
        }
    } elseif ($type==2) {
        if ($maxCommission<13) {
            return 1.3;
        } else {
            return 1.8;
        }
    } elseif ($type==3) {
        if ($ratio<5500) {
            return round($maxCommission*0.92,2);
        } else {
            return round($maxCommission*0.83,2);
        }
    }
}

/**
 * [normal_return description]
 * @param  [type]  $maxCommission [description]
 * @param  [type]  $ratio         [description]
 * @param  integer $type          1-美团2-饿了么3-云瞻美团活动
 * @return [type]                 [description]
 */
function normal_return($maxCommission,$ratio,$type=1)
{
    if ($type==1) {
        if ($ratio<5500) {
            return round($ratio*0.91/100,2);
        } else {
            return round($ratio*0.85/100,2);
        }
    } elseif ($type==3) {
        if ($ratio<5500) {
            return round($ratio*0.91/100,2);
        } else {
            return round($ratio*0.85/100,2);
        }
    }
}